package com.ljk.studywebsocket.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

/**
 * 默认的webSocket配置
 * ws://localhost:8080/func1/ws
 */
@Configuration
@EnableWebSocket
public class WebSocketConfiguration implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new DefaultHandler(), "/func1/ws") // api  对应controller
//                .addInterceptors(new DefaultInterceptor()) // 拦截器
                .addInterceptors(new HttpSessionHandshakeInterceptor()) // spring自带的拦截器(内置拦截器将HTTP会话属性传递给WebSocket),当然也可以自己拓展拦截器
                .setAllowedOrigins("*");
    }

    /** 可选配置可省略 */
    @Bean
    public ServletServerContainerFactoryBean createWebSocketContainer() {
        ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean();
        container.setMaxTextMessageBufferSize(8192);
        container.setMaxBinaryMessageBufferSize(8192);
        return container;
    }

}
